import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import db from '../database/db';

export interface Draft {
  id: string;
  title: string;
  content: string;
  images: string[];
  status: 'draft' | 'review' | 'ready';
  createTime: string;
  updateTime: string;
}

interface DraftState {
  drafts: Draft[];
  loading: boolean;
  error: string | null;
  
  // Actions
  fetchDrafts: () => Promise<void>;
  addDraft: (draft: Omit<Draft, 'id' | 'createTime' | 'updateTime'>) => Promise<void>;
  updateDraft: (id: string, updates: Partial<Draft>) => Promise<void>;
  deleteDraft: (id: string) => Promise<void>;
  getDraftsByStatus: (status: Draft['status']) => Draft[];
}

export const useDraftStore = create<DraftState>()(
  devtools(
    (set, get) => ({
      drafts: [],
      loading: false,
      error: null,

      fetchDrafts: async () => {
        set({ loading: true, error: null });
        try {
          const stmt = db.prepare('SELECT * FROM drafts ORDER BY updateTime DESC');
          const drafts = stmt.all() as any[];
          // 解析images字符串为数组
          const draftsWithImages = drafts.map(draft => ({
            ...draft,
            images: draft.images ? JSON.parse(draft.images) as string[] : []
          })) as Draft[];
          set({ drafts: draftsWithImages, loading: false });
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      addDraft: async (draft) => {
        set({ loading: true, error: null });
        try {
          const id = Date.now().toString();
          const now = new Date().toISOString();
          const newDraft: Draft = {
            ...draft,
            id,
            createTime: now,
            updateTime: now,
          };

          const stmt = db.prepare(`
            INSERT INTO drafts (id, title, content, images, status, createTime, updateTime)
            VALUES (?, ?, ?, ?, ?, ?, ?)
          `);
          stmt.run(
            newDraft.id,
            newDraft.title,
            newDraft.content,
            JSON.stringify(newDraft.images),
            newDraft.status,
            newDraft.createTime,
            newDraft.updateTime
          );

          set(state => ({
            drafts: [newDraft, ...state.drafts],
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      updateDraft: async (id, updates) => {
        set({ loading: true, error: null });
        try {
          const now = new Date().toISOString();
          const updateFields = Object.keys(updates)
            .filter(key => key !== 'id')
            .map(key => `${key} = ?`)
            .join(', ');

          const stmt = db.prepare(`
            UPDATE drafts 
            SET ${updateFields}, updateTime = ?
            WHERE id = ?
          `);

          const values = [...Object.values(updates), now, id];
          stmt.run(...values);

          set(state => ({
            drafts: state.drafts.map(draft =>
              draft.id === id ? { ...draft, ...updates, updateTime: now } : draft
            ),
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      deleteDraft: async (id) => {
        set({ loading: true, error: null });
        try {
          const stmt = db.prepare('DELETE FROM drafts WHERE id = ?');
          stmt.run(id);

          set(state => ({
            drafts: state.drafts.filter(draft => draft.id !== id),
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      getDraftsByStatus: (status) => {
        return get().drafts.filter(draft => draft.status === status);
      },
    }),
    {
      name: 'draft-store',
    }
  )
); 